package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.ContactItem;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.List;


public class ContactListAdapter extends RecyclerView.Adapter<ContactListAdapter.ViewHolder> {

    private static final String TAG = "ContactListAdapter";
    private Context context;
    private LayoutInflater mLayoutInflater;
    private List<ContactItem> itemList;
    private InteractionListener listener;

    public ContactListAdapter(Context context, List<ContactItem> result) {
        mLayoutInflater = LayoutInflater.from(context);
        this.context = context;
        this.itemList = result;
    }

    public ContactListAdapter(Context context, List<ContactItem> result, InteractionListener mOnItemClickListener) {
        mLayoutInflater = LayoutInflater.from(context);
        this.context = context;
        this.itemList = result;
        this.listener = mOnItemClickListener;
    }


    public void setOnItemClickListener(InteractionListener mOnItemClickListener) {
        this.listener = mOnItemClickListener;
    }

    @Override
    public int getItemViewType(int position) {
        if (itemList.size() == 0) {
            return ContactItem.CONTACT_ITEM_NO_DATA;
        }
        return itemList.get(position).getItemType();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == ContactItem.CONTACT_ITEM_TYPE_PARENT) {
            return new ViewHolder(mLayoutInflater.inflate(R.layout.tx_expandablelist_item_parent, null));
        } else {
            return new ViewHolder(mLayoutInflater.inflate(R.layout.tx_expandableitem_child, null));
        }
//        else {
//            return new ViewHolder(mLayoutInflater.inflate(R.layout.tx_contact_item_no_data, null));
//        }

    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        if (itemList.size() == 0) {
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.addContact();
                }
            });
            return;
        }

        final ContactItem item = itemList.get(position);
        holder.divider.setVisibility(View.VISIBLE);
        if (item.getItemType() == ContactItem.CONTACT_ITEM_TYPE_PARENT) {
            holder.tv_name.setText(item.getGroupName());
            if (item.isDisplayChildContact()) {

                //  holder.iv_arrow.setImageResource(R.drawable.tx_arrow_down_blue);
                holder.iv_arrow.setRotation(-180);
                showLongDivider(holder);
            } else {
                // holder.iv_arrow.setImageResource(R.drawable.tx_arrow_down);
                holder.iv_arrow.setRotation(0);
                showShortDivider(holder);
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isDisplayChildContact()) {//当前子联系人是展开状态，那就收折
                        hideChildItem(item, position, holder);

                    } else {//不是展开状态，就显示
                        displayChildItem(item, position, holder, true);
                    }
                }
            });
        } else {
            final Contact contact = item.getContact();
            final User targetUser = contact.getTargetUser();
            if (targetUser == null) {
                return;
            }
            holder.tv_name.setText(targetUser.getUsername());
            //Glide.with(context).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(holder.iv_avatar);
            GlideLoadUtils.glideLoad(context, targetUser.getAvatar(), holder.iv_avatar);

            if (contact.getStatus() != null && !contact.getStatus().equals(Constant.CONTACT_STATUS_MUTUAL)) {//对方已经把自己删除了，现属于单边联系人关系，显示半透明背景
                holder.itemView.setBackgroundColor(context.getResources().getColor(R.color.transparent_black));
            } else {
                holder.itemView.setBackgroundColor(context.getResources().getColor(R.color.transparent));
            }
            holder.rl_theMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.showMore(position, holder);
                    }
                }
            });
            holder.rl_userInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Conversation c2cConversation = IMSClientBootstrap.getInstance().getConversationService().getC2cConversation(targetUser.getuId());
                    if (c2cConversation!=null){
                        c2cConversation.openConversation(context);
                    }
//                    Intent intent = new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser);
//                    intent.putExtra("CONTACT_STATUS", contact.getStatus());
//                    context.startActivity(intent);
                }
            });
        }


    }

    void hideChildItem(ContactItem item, int position, final ViewHolder holder) {
        item.setDisplayChildContact(false);
        notifyItemRangeRemoved(position + 1, item.getChildContactList().size());
        int count = itemList.size() - 1 - (position + 1);
        Log.d(TAG, "hideChildItem: " + count);
        itemList.removeAll(item.getChildContactList());
        notifyItemRangeChanged(position + 1, count);//当前点击项之后的item 全都需要刷新
//        ViewAnimator.animate(holder.iv_arrow).rotation(0).duration(300).onStop(new AnimationListener.Stop() {
//            @Override
//            public void onStop() {
//                holder.iv_arrow.setImageResource(R.drawable.tx_arrow_down);
//
//            }
//        }).start();
        holder.iv_arrow.setRotation(0);
        showShortDivider(holder);
    }

    private void showShortDivider(ViewHolder holder) {
        // holder.divider.setBackgroundColor(context.getResources().getColor(R.color.gray_normal));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dpToPx(1, context));
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_START, R.id.tv_name);
        holder.divider.setLayoutParams(params);
    }

    public void displayChildItem(ContactItem item, int position, final ViewHolder holder, boolean needRefresh) {
        item.setDisplayChildContact(true);
        if (position > itemList.size() - 1) {
            Log.e(TAG, "displayChildItem: 出现position越界情况，，，，，，，，，，，，，，，，，，，，，");
        }

        if (position >= itemList.size() - 1) {
            itemList.addAll(item.getChildContactList());
        } else {
            itemList.addAll(position + 1, item.getChildContactList());
        }
        int size = item.getChildContactList().size();

        notifyItemRangeInserted(position + 1, size);
        if (needRefresh) {
            int count = itemList.size() - 1 - (position + size);
            Log.d(TAG, "displayChildItem: " + count);
            notifyItemRangeChanged(position + 1 + size, count);//从新添加的item的后面一直到结尾，全部刷新
        }


//        ViewAnimator.animate(holder.iv_arrow).rotation(-180).duration(300).onStop(new AnimationListener.Stop() {
//            @Override
//            public void onStop() {
//                holder.iv_arrow.setImageResource(R.drawable.tx_arrow_down_blue);
//            }
//        }).start();
        holder.iv_arrow.setRotation(180);
        showLongDivider(holder);
    }

    private void showLongDivider(ViewHolder holder) {
        // holder.divider.setBackgroundColor(context.getResources().getColor(R.color.gray_pressed));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dpToPx(1, context));
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        holder.divider.setLayoutParams(params);
    }

    @Override
    public int getItemCount() {
        return itemList.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_arrow;

        ImageView iv_avatar;

        TextView tv_name;

        View rl_userInfo;

        View rl_theMore;

        public ProgressBar progressBar;

        public View divider;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_arrow = itemView.findViewById(R.id.iv_arrow);
            iv_avatar = itemView.findViewById(R.id.iv_avatar);
            tv_name = itemView.findViewById(R.id.tv_name);
            rl_userInfo = itemView.findViewById(R.id.rl_to_chat);
            rl_theMore = itemView.findViewById(R.id.rl_the_more);
            divider = itemView.findViewById(R.id.divider);
            progressBar = itemView.findViewById(R.id.progress_bar);
        }

    }


    public interface InteractionListener {
        void showMore(int position, ViewHolder viewHolder);

        void addContact();
    }


}
